import 'package:aitao_flutter/request/api.dart';
import 'package:aitao_flutter/res/r.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/edgeInsets_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:aitao_flutter/utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../common_ui/circle_avatar.dart';
import '../const/common_const.dart';
import '../model/rank_user_model.dart';
import '../request/requestManager.dart';
import '../style/color_style.dart';
import '../style/text_style.dart';

class BoardPage extends StatefulWidget {
  const BoardPage({Key? key}) : super(key: key);

  @override
  State<BoardPage> createState() => _BoardPageState();
}

class _BoardPageState extends State<BoardPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  final List<String> _tabList = [
    BoardStringConst.hotBoardText,
    BoardStringConst.localBoardText,
    BoardStringConst.giftBoardText,
    BoardStringConst.guardBoardText
  ];
  int _tabIndex = 0;
  int _dayTypeIndex = 0;
  int type = 5; // 默认获取昨日榜
  late TabController tabController;
  final List<RankUserModel> _boardList = [];
  RankUserModel? firstUser;
  RankUserModel? secondUser;
  RankUserModel? thirdUser;
  @override
  void initState() {
    super.initState();
    tabController =
        TabController(length: _tabList.length, vsync: this, initialIndex: 0);
    getBoardListData();
  }

  String getRequestUrl() {
    if (_tabIndex == 0) {
      return API.getRankLove;
    } else if (_tabIndex == 1) {
      return API.getRankWealth;
    } else if (_tabIndex == 2) {
      return API.getRankGifts;
    } else {
      return API.getRankGuard;
    }
  }

  void getBoardListData() async {
    _boardList.clear();
    firstUser = null;
    secondUser = null;
    thirdUser = null;
    var result = await RequestManager()
        .post(getRequestUrl(), params: {'page': 1, 'type': type});
    if (result != null && result['code'] == 0) {
      List tempList = result['data']['list'];
      for (var item in tempList) {
        RankUserModel userModel = RankUserModel.fromJson(item);
        _boardList.add(userModel);
      }
      if (_boardList.isNotEmpty) {
        // 第一名
        firstUser = _boardList[0];
      }
      if (_boardList.length > 1) {
        // 第二名
        secondUser = _boardList[1];
      }
      if (_boardList.length > 2) {
        // 第三名
        thirdUser = _boardList[2];
      }
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: Container(
          decoration:
              const BoxDecoration(gradient: ColorStyle.boardBackgroundColor),
          child: Column(children: [
            Container(
              padding: const EdgeInsets.fromLTRB(14, 24, 14, 10),
              child:
                  Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
                Expanded(
                    child: Container(
                  alignment: Alignment.center,
                  child: TabBar(
                    isScrollable: true,
                    onTap: (index) {
                      setState(() {
                        type = 5;
                        _dayTypeIndex = 0;
                        _tabIndex = index;
                        getBoardListData();
                      });
                    },
                    labelColor: ColorStyle.whiteColor,
                    indicatorColor: ColorStyle.themeColor,
                    indicatorSize: TabBarIndicatorSize.label,
                    indicatorPadding: const EdgeInsets.only(left: 8, right: 8),
                    indicatorWeight: 3,
                    labelPadding: const EdgeInsets.only(bottom: 5),
                    // labelStyle: Styles.boldText_16,
                    // unselectedLabelStyle: const TextStyle(
                    //     color: ColorStyle.ashGreyColor, fontSize: 15),
                    tabs: _tabList.asMap().entries.map((e) {
                      return Padding(
                          padding: const EdgeInsets.only(left: 15, right: 15),
                          child: Text(
                            e.value,
                            style: e.key == _tabIndex
                                ? Styles.whiteBoldText_16
                                : const TextStyle(
                                    color: ColorStyle.whiteColor, fontSize: 15),
                          ));
                    }).toList(),
                    controller: tabController,
                  ),
                )),
              ]),
            ),
            Expanded(
                child: CustomScrollView(
              slivers: [
                _boardTitleWidget(),
                _boardTopRankWidget(),
                _rankContainerWidget()
              ],
            ))
          ])),
    );
  }

  Widget _boardTitleWidget() {
    return SliverToBoxAdapter(
        child: Center(
      child: SizedBox(
        width: (88 * 3).w,
        // color: ColorStyle.orangeColor,
        child: CupertinoSegmentedControl(
          onValueChanged: (value) {
            _dayTypeIndex = value;
            setState(() {
              if (value == 0) {
                type = 5;
              } else if (value == 1) {
                type = 4;
              } else if (value == 2) {
                type = 1;
              }
            });
            getBoardListData();
          },
          children: const {
            0: Text(
              BoardStringConst.yesterdayBoardText,
            ),
            1: Text(
              BoardStringConst.todayBoardText,
            ),
            2: Text(BoardStringConst.weekBoardText),
          },
          //当前选中的索引
          groupValue: _dayTypeIndex,
          //选中的背景颜色
          selectedColor: ColorStyle.themeColor,
          //未选中的背景颜色
          unselectedColor: Colors.white,
          //边框颜色
          borderColor: ColorStyle.themeColor,
          //按下的颜色
          // pressedColor: ColorsUtil.hexToColor("#52596D").withOpacity(0.4),
        ),
      ),
    ));
  }

  Widget _boardTopRankWidget() {
    return SliverToBoxAdapter(
      child: Stack(
        children: [
          _firstRank(),
          Positioned(
            left: 40,
            child: _secondRank(),
          ),
          Positioned(
            right: 40,
            child: _thirdRank(),
          ),
        ],
      ),
    );
  }

  Widget _firstRank() {
    return Container(
      padding: const EdgeInsets.only(bottom: 80),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(ImagePath.assetsBoardRankTop1Icon),
          Box.vBox(2),
          // 头像
          Stack(
            clipBehavior: Clip.none,
            alignment: Alignment.center,
            children: [
              Image.asset(
                ImagePath.assetsBoardRankTop1BG,
                fit: BoxFit.fill,
              ),
              Positioned(
                  top: 28.w,
                  child: SizedBox(
                      width: 60.w,
                      height: 60.w,
                      child: firstUser == null
                          ? ClipRRect(
                              borderRadius: RadiusStyle.radiusAll(30.w),
                              child: Image.asset(
                                ImagePath.assetsBoardTop1PlaceHolder,
                                fit: BoxFit.fill,
                              ),
                            )
                          : CircleAvatarWidget(
                              url: firstUser!.avatar ?? '',
                              gender: firstUser!.gender ?? 1))),
              Positioned(
                  bottom: -10,
                  child: Image.asset(ImagePath.assetsBoardRankTop1Num))
            ],
          ),
          Box.vBox10,
          // 昵称
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                firstUser == null
                    ? BoardStringConst.placeholderText
                    : firstUser?.nickname ?? BoardStringConst.placeholderText,
                style: Styles.whiteText_16,
              ),
              Box.hBox5,
              Visibility(
                  visible: firstUser == null
                      ? false
                      : firstUser?.vip != 2
                          ? true
                          : false,
                  child: Image.asset(CommonUtils.setVipImagePath(
                      firstUser?.vip ?? 2, firstUser?.vipLevel ?? 0))),
            ],
          ),
          Box.vBox5,
        ],
      ),
    );
  }

  Widget _secondRank() {
    return Container(
      padding: const EdgeInsets.only(top: 50),
      child: Column(
        children: [
          Image.asset(ImagePath.assetsBoardRankTop2Icon),
          Box.vBox(2),
          // 头像
          Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                  child: Container(
                      width: 60.w,
                      height: 60.w,
                      padding: EdgeInsetsStyle.all(3),
                      decoration: BoxDecoration(
                          borderRadius: RadiusStyle.radiusAll(30.w),
                          color: ColorStyle.setColor(0xFFd8e2f3)),
                      child: secondUser == null
                          ? ClipRRect(
                              borderRadius: RadiusStyle.radiusAll(30.w),
                              child: Image.asset(
                                ImagePath.assetsBoardTop2PlaceHolder,
                                fit: BoxFit.fill,
                              ),
                            )
                          : CircleAvatarWidget(
                              url: secondUser!.avatar ?? '',
                              gender: secondUser!.gender ?? 1))),
              Positioned(
                  bottom: 0,
                  child: Image.asset(ImagePath.assetsBoardRankTop2Num))
            ],
          ),
          // 昵称
          Row(
            children: [
              Text(
                secondUser == null
                    ? BoardStringConst.placeholderText
                    : secondUser?.nickname ?? BoardStringConst.placeholderText,
                style: Styles.whiteText_16,
              ),
              Box.hBox5,
              Visibility(
                  visible: secondUser == null
                      ? false
                      : secondUser?.vip != 2
                          ? true
                          : false,
                  child: Image.asset(CommonUtils.setVipImagePath(
                      secondUser?.vip ?? 2, secondUser?.vipLevel ?? 0))),
            ],
          ),
          Box.vBox5,
          Text(
            '距上一名:${secondUser?.gapMoney ?? 0}',
            style: Styles.whiteText_12,
          ),
        ],
      ),
    );
  }

  Widget _thirdRank() {
    return Container(
      padding: const EdgeInsets.only(top: 50),
      child: Column(
        children: [
          Image.asset(ImagePath.assetsBoardRankTop3Icon),
          Box.vBox(2),
          // 头像
          Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                  child: Container(
                      width: 60.w,
                      height: 60.w,
                      padding: EdgeInsetsStyle.all(3),
                      decoration: BoxDecoration(
                          borderRadius: RadiusStyle.radiusAll(30.w),
                          color: ColorStyle.setColor(0xFFd8e2f3)),
                      child: thirdUser == null
                          ? ClipRRect(
                              borderRadius: RadiusStyle.radiusAll(30.w),
                              child: Image.asset(
                                ImagePath.assetsBoardTop3PlaceHolder,
                                fit: BoxFit.fill,
                              ),
                            )
                          : CircleAvatarWidget(
                              url: thirdUser!.avatar ?? '',
                              gender: thirdUser!.gender ?? 1))),
              Positioned(
                  bottom: 0,
                  child: Image.asset(ImagePath.assetsBoardRankTop3Num))
            ],
          ),
          // 昵称
          Row(
            children: [
              Text(
                thirdUser == null
                    ? BoardStringConst.placeholderText
                    : thirdUser?.nickname ?? BoardStringConst.placeholderText,
                style: Styles.whiteText_16,
              ),
              Box.hBox5,
              Visibility(
                  visible: thirdUser == null
                      ? false
                      : thirdUser?.vip != 2
                          ? true
                          : false,
                  child: Image.asset(CommonUtils.setVipImagePath(
                      thirdUser?.vip ?? 2, thirdUser?.vipLevel ?? 0))),
            ],
          ),
          Box.vBox5,
          Text(
            '距上一名:${thirdUser?.gapMoney ?? 0}',
            style: Styles.whiteText_12,
          ),
        ],
      ),
    );
  }

  Widget _rankContainerWidget() {
    return SliverToBoxAdapter(
      child: Visibility(
          visible: true,
          child: Container(
            margin: EdgeInsetsStyle.customMargin(14, 0, 14, 14),
            decoration: BoxDecoration(
                color: ColorStyle.whiteColor,
                borderRadius: RadiusStyle.radiusAll(25)),
            child: ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                return _rankItemWidget(index);
              },
              itemCount: _boardList.isEmpty ? 0 : _boardList.length - 3,
            ),
          )),
    );
  }

  Widget _rankItemWidget(int index) {
    RankUserModel model = _boardList[index + 3];
    return Container(
      padding: EdgeInsetsStyle.edgeInsets(20, 15),
      child: Row(
        children: [
          Text(
            (index + 4).toString(),
            style: Styles.normalText_15,
          ),
          Box.hBox15,
          CircleAvatarWidget(
            url: model.avatar ?? '',
            gender: model.gender ?? 1,
            imgWidth: 40,
            imgHeight: 40,
          ),
          Box.hBox10,
          Text(
            model.nickname ?? '',
            style: Styles.normalText_15,
          ),
          const Spacer(),
          Text(
            '距上一名${model.gapMoney}',
            style: Styles.normalText_12,
          ),
        ],
      ),
    );
  }
}
